<?php
namespace app\store\controller\checker;

use app\store\controller\Base;
use app\store\controller\Weixin;
use think\Db;

class Sign extends Base
{

    /*
     * wangtiantian
     * 学生签到--扫码签到
     * @return mixed
     */
    public function student_sign(){

        if(request()->isAjax()){
            $data = json_decode(input('data'),true);

            if ($data['errMsg']  == "scanQRCode:ok"){
                // 获取学生学号
                $stu_no = $data['resultStr'];
                if($stu_no){
                    $this->success('请点击查询','',$stu_no);
                }else{
                    $this->error('信息有误，请输入正确信息') ;
                }
            }

        }
    }

    /*
     * 手动签到--查找当前时间所接近的两个时间段的学生信息
     *wangtiantian
     */

    public  function  hand_sign(){

        if(request()->isAjax()){

        $key  = input('keyword');
        $res =   Db::name('student')
                    ->where('name|stu_no' ,'like','%'.$key.'%')->find();
            $data = '';
            $suju = '';
            if($res){
                $time=time();

                // 获取当日零点的时间戳
                $today = strtotime(date("Y-m-d"),time());
                // 获取今天是星期几
                $week =date('w',$time);
                // 学生id
                $stu_id= $res['stu_id'];
                $stu_no= $res['stu_no'];
                // 门店签到员
                $checker_id = $this->uid;
                // 查询集体班$many  查到课程id
                $many = Db::name('stu_many_time')->where('stu_id',$stu_id) ->where('is_del',0)->select();
                if(!empty($many)){

                    foreach ($many as $k=>$v){

                        $m = Db::name('course_time')
                            ->where('course_id',$v['course_id'])
//                            ->where('teacher_id',$teacher_id)
                            ->where('week_day',$week)
                            ->where('is_del',0)
                            ->select();
                        if(!empty($m)){
                            foreach ($m as $k1 =>$v1){
                                $data1['period_id']  = $v1['period_id'];
                                $data1['course_id']  = $v['course_id'];
                                $data1['course_name']  = $v['course_name'];
                                //  类型 1 集体班  2  一对一或一对多
                                $data1['type']  =1;
                                $data[] =$data1;
                            }
                        }
                    }
                }
                // 查询一对一 、一对多、学生信息
                $one = Db::name('stu_one_time')
                    ->where('stu_id',$stu_id)
//                    ->where('teacher_id',$teacher_id)
                    ->where('week_day',$week)
                    ->where('is_del',0)
                    ->select();

                if($one != null){

                    foreach ($one  as $k =>$v){
                        $course_name= Db::name('course')->where('id',$v['course_id'])->value('course_name');
                        $data2['period_id']  = $v['period_id'];
                        $data2['course_id']  = $v['course_id'];
                        $data2['course_name']  = $course_name;
                        //  类型 1 集体班  2  一对一或一对多
                        $data2['type']  =   2;
                        $data[] =$data2;
                    }

                }


                if($data){
                    foreach ($data as $k =>$v){
                        $perdiod = Db::name('period')->where('id',$v['period_id'])->find();
                        $t['start'] =$today+ $perdiod['start_hour']*60*60 +$perdiod['start_minute']*60;
                        $t['end'] =$today+ $perdiod['end_hour']*60*60 +$perdiod['end_minute']*60;

                        // 判断该生当日是否已签到
                        $stu_sign = Db::name('student_sign')
                            ->where('stu_no',$stu_no)
                            ->where('period_id',$v['period_id'])
                            ->where('time','>',$today)
//                            ->where('time','<',$t['end'])
                            ->find();
                        if($stu_sign){
                            $sign_info['name'] =$res['name'];
                            $sign_info['stu_no'] =$stu_no;
                            $sign_info['status'] =$stu_sign['status'];
                            $sign_info['period_id'] =$v['period_id'];
                            $sign_info['course_id'] =$v['course_id'];
                            $sign_info['start_time'] = $perdiod['start_hour'].":".$perdiod['start_minute'];
                            $sign_info['end_time']   = $perdiod['end_hour'].":".$perdiod['end_minute'];
                        }
                        if(!$stu_sign){
                            $sign_info['name'] =$res['name'];
                            $sign_info['stu_no'] =$stu_no;
                            $sign_info['status'] =0;
                            $sign_info['period_id'] =$v['period_id'];
                            $sign_info['course_id'] =$v['course_id'];
                            $sign_info['start_time'] = $perdiod['start_hour'].":".$perdiod['start_minute'];
                            $sign_info['end_time']   = $perdiod['end_hour'].":".$perdiod['end_minute'];
                        }
                        $suju[] =$sign_info;
                    }
                }


                if($suju){
                    $this->success('查询成功','',$suju);
                }else{
                    $this->error('查询失败');
                }
            }
            else{
                $this->error('无此学生信息');
            }

        }

        //微信 js config
        $weixin = new Weixin($this->shop_id);
        $url = request()->domain() . $this->request->url();
        $js_config = $weixin->js_config($url);
        $this->assign('jsconfig', $js_config);


        // 数据准备
        $time =time();

        // 获取当日零点的时间戳
        $today = strtotime(date("Y-m-d"),time());

        // 获取今天是星期几
        $week =date('w',$time);

        $period = Db::name('period')->select();

        $near ='';
        $twoid = '';
        $t_course = '';
        $stu_info = '';
        $zz = '';
        $res='';

        // 计算与当前时间最相近的时间段
        foreach ($period  as $k => $v){
            $start_hour = $v['start_hour'];
            $start_minute = $v['start_minute'];
            $end_hour = $v['end_hour'];
            $end_minute = $v['end_minute'];

            $start  = $today+$start_hour*60*60 +$start_minute*60;
            $end    = $today+$end_hour*60*60+$end_minute*60;

            // 获取正在上课的时间段
            if($start < $time && $end>=$time){
                $p['pid1'] = $v['id'];
                $p['start_hour'] = $start_hour;
                $p['start_minute'] = $start_minute;
                $p['end_hour'] = $end_hour;
                $p['end_minute'] = $end_minute;
                $p['min'] = null;

                $near[] = $p;

            }
            // 获取下一个的时间段
            elseif ($start>$time){

                $p['pid1'] = $v['id'];
                $p['start_hour'] = $start_hour;
                $p['start_minute'] = $start_minute;
                $p['end_hour'] = $end_hour;
                $p['end_minute'] = $end_minute;
                $p['min'] = $start-$time;
                $near[] = $p;
            }


        }

        //  遍历所有 取出两个的时间段（当前、下一个）
        if(is_array($near)){
            foreach ($near  as $k1 =>$v1)
            {
                // 取当前时间段
                if ($v1['min'] == null){
                    $close['pid'] = $v1['pid1'];
                    $close['start_hour'] = $v1['start_hour'];
                    $close['start_minute'] = $v1['start_minute'];
                    $close['end_hour'] = $v1['end_hour'];
                    $close['end_minute'] = $v1['end_minute'];
                    $close['min'] = $v1['min'];

                    $twoid[] = $close;
                    unset($near[$k1]);//删除
                }
            }

        }else{
            $this->assign('shop_id',$this->shop_id);
            $this->assign('res',$res);
            return $this->fetch();
//            $this->error('该时间段无课程安排，请稍后查询');
        }

        // 取下一个时间段
        if (! function_exists('list_sort_by'))
        {
            function list_sort_by($list, $field, $sortby = 'asc')
            {
                if (is_array($list))
                {
                    $refer = $resultSet = array();
                    foreach ($list as $i => $data)
                    {
                        $refer[$i] = &$data[$field];
                    }
                    switch ($sortby)
                    {
                        case 'asc': // 正向排序
                            asort($refer);
                            break;
                        case 'desc': // 逆向排序
                            arsort($refer);
                            break;
                        case 'nat': // 自然排序
                            natcasesort($refer);
                            break;
                    }
                    foreach ($refer as $key => $val)
                    {
                        $resultSet[] = &$list[$key];
                    }
                    return $resultSet;
                }
                return false;
            }
        }
        $new_list = list_sort_by($near, 'min', 'asc');
        $min_list = reset($new_list);
        // 获取差值最小的一列
        if($min_list){
            $close['pid'] = $min_list['pid1'];
            $close['start_hour'] = $min_list['start_hour'];
            $close['start_minute'] = $min_list['start_minute'];
            $close['end_hour'] = $min_list['end_hour'];
            $close['end_minute'] = $min_list['end_minute'];
            $close['min'] = $v1['min'];
            $twoid[] = $close;
        }

        // 查找当日 该老师的课程表

        foreach ($twoid as $k2=>$v2){

            // 查询课程时间段是否匹配
            $teacher_course = Db::name('course_time')
//                ->where('teacher_id',$this->uid)
                ->where('week_day',$week)
                ->where('period_id',$v2['pid'])
                ->find();
            $one_course = Db::name('stu_one_time')
//                ->where('teacher_id',$this->uid)
                ->where('week_day',$week)
                ->where('period_id',$v2['pid'])
                ->find();

            if($teacher_course){
                $teacher['course_id'] =  $teacher_course['course_id'];
                $teacher['period_id'] =  $teacher_course['period_id'];
                $teacher['class_id']  =  $teacher_course['class_id'];
                $teacher['start_hour']  =  $v2['start_hour'];
                $teacher['start_minute']  =  $v2['start_minute'];
                $teacher['end_hour']  =  $v2['end_hour'];
                $teacher['end_minute']  =  $v2['end_minute'];


                $t_course[]  = $teacher;
            }

            if($one_course){
                $teacher['course_id'] =  $one_course['course_id'];
                $teacher['period_id'] =  $one_course['period_id'];
                $teacher['class_id']  =  $one_course['class_id'];
                $teacher['start_hour']  =  $v2['start_hour'];
                $teacher['start_minute']  =  $v2['start_minute'];
                $teacher['end_hour']  =  $v2['end_hour'];
                $teacher['end_minute']  =  $v2['end_minute'];


                $t_course[]  = $teacher;
            }


        }

        if($t_course){
            foreach ( $t_course as $k3 =>$v3){
                $course_name= Db::name('course')->where('id',$v3['course_id'])->value('course_name');
                // 集体班
                $many =  Db::name('stu_many_time')->where('course_id',$v3['course_id'])->select();
                // 一对一 或一对多
                $one =  Db::name('stu_one_time')
                    ->where('course_id',$v3['course_id'])
                    ->where('period_id',$v3['period_id'])
                    ->where('class_id',$v3['class_id'])
//                    ->where('teacher_id',$this->uid)
                    ->where('week_day',$week)
                    ->select();
                if($many){
                    foreach ($many  as $k4 =>$v4){
                        $stu = Db::name('student')->where('stu_id',$v4['stu_id'])->find();
                        $student['stu_id'] = $stu['stu_id'];
                        $student['stu_no'] = $stu['stu_no'];
                        $student['name']   = $stu['name'];
                        $student['start']  = $v3['start_hour'].':'.$v3['start_minute'];
                        $student['end']    = $v3['end_hour'].':'.$v3['end_minute'];
                        $student['course_id']    = $v3['course_id'];
                        $student['course_name']    = $course_name;
                        $student['period_id']    = $v3['period_id'];

                        $stu_info[] = $student;
                    }

                }elseif ($one){

                    foreach ($one  as $k5 =>$v5){
                        $stu = Db::name('student')->where('stu_id',$v5['stu_id'])->find();
                        $student['stu_id'] = $stu['stu_id'];
                        $student['stu_no'] = $stu['stu_no'];
                        $student['name']   = $stu['name'];
                        $student['start']  = $v3['start_hour'].':'.$v3['start_minute'];
                        $student['end']    = $v3['end_hour'].':'.$v3['end_minute'];
                        $student['course_id']    = $v3['course_id'];
                        $student['course_name']    = $course_name;
                        $student['period_id']    = $v3['period_id'];

                        $stu_info[] = $student;
                    }


                }

            }
        }


        if($stu_info){
            foreach ($stu_info as $k6 =>$v6){
                $sign = Db::name('student_sign')
                                ->where('period_id',$v6['period_id'])
                                ->where('stu_no',$v6['stu_no'])
                                ->where('time','>',$today)
                                ->find();
                if(!$sign){
                    $stu_s['status'] = 0;
                    $stu_s['stu_id'] = $v6['stu_id'];
                    $stu_s['stu_no'] = $v6['stu_no'];
                    $stu_s['name']   = $v6['name'];
                    $stu_s['start']  = $v6['start'];
                    $stu_s['end']    = $v6['end'];
                    $stu_s['course_id']    = $v6['course_id'];
                    $stu_s['course_name']    = $v6['course_name'];
                    $stu_s['period_id']    = $v6['period_id'];

                    $zz[] = $stu_s;
                }
            }
        }
//        echo "<pre>";
//        print_r($zz);
//        die;
        $this->assign('res',$zz);
        $this->assign('shop_id',$this->shop_id);
        return $this->fetch();
    }


    /*
     * 搜索后的操作按钮
     * 点击按钮-签到、请假、迟到
     * wangtiantian
     */
    public function sign(){
        if(request()->isAjax()){

            // 获取当日零点的时间戳
            $today = strtotime(date("Y-m-d"),time());

            // 获取学生学号
            $stu_no = input('stu_no');
            $stu_info = Db::name('student')->where('stu_no',$stu_no)->find();
            $course_name = Db::name('course')->where('id',input('course_id'))->value('course_name');
            $data['stu_no'] = $stu_no;
            $data['status'] = input('status');
            $data['time'] = time();
            $data['period_id'] = input('period_id');
            $data['type'] = 2;
            $data['identity_id'] = $this->uid;
            $data['course_name'] =$course_name ;
            // 判断该生当日是否已签到
            $stu_sign = Db::name('student_sign')
                ->where('stu_no',$stu_no)
                ->where('period_id',$data['period_id'])
                ->where('course_name', $data['course_name'])
                ->where('time','>',$today)
                ->find();
            if(!$stu_sign){
                $res = db('student_sign')->insertGetId($data);
                if($res){
                    $openid = Db::name('parent_bind_student')->where('stu_id',$stu_info['stu_id'])->value('parent_openid');
                    if($openid){

                        if($data['status'] == 1){
                            $sta_name = "已到校";
                        }
                        if($data['status'] == 2){
                            $sta_name = "请假";
                        }
                        if($data['status'] == 3){
                            $sta_name = "迟到";
                        }
                        $a=  $this->publish_ok1($openid,$stu_info['name'],$sta_name);
                        if($a){
                            $this->success('操作成功');
                        }
                    }else{
                        $this->success('操作成功');
                    }
                }else{
                    $this->error('操作失败');
                }
            }
            else{
                $this->error('请勿重复操作');
            }



        }

    }

    /*
     * 进入页面后列表中操作按钮
     * 点击按钮-签到、请假、迟到
     * wangtiantian
     */
    public function sign1(){
        if(request()->isAjax()){
             $time = time();
            // 获取当日零点的时间戳
            $today = strtotime(date("Y-m-d"),$time);
            // 获取学生学号
            $stu_no = input('stu_no');
            $status = input('status');
            $period_id = input('period_id');

            $stu_info = Db::name('student')->where('stu_no',$stu_no)->find();

            $data['status'] = $status;
            $data['period_id'] = $period_id;
            $data['time'] = $time;
            $data['stu_no'] = $stu_no;
            $data['course_name'] = input('c_name');
            $data['identity_id'] = $this->uid;
            $data['type'] = 1;
            // 判断该生当日是否已签到
            $stu_sign = Db::name('student_sign')
                ->where('stu_no',$stu_no)
                ->where('period_id',$data['period_id'])
                ->where('course_name', $data['course_name'])
                ->where('time','>',$today)
                ->find();
            if(!$stu_sign){
                $res = db('student_sign')->insertGetId($data);
                if($res){
                    $openid = Db::name('parent_bind_student')->where('stu_id',$stu_info['stu_id'])->value('parent_openid');
                    if($openid){

                        if($status == 1){
                            $sta_name = "已到校";
                        }
                        if($status == 2){
                            $sta_name = "请假";
                        }
                        if($status == 3){
                            $sta_name = "迟到";
                        }
                        $a=  $this->publish_ok1($openid,$stu_info['name'],$sta_name);
                        if($a){
                            $this->success('操作成功');
                        }
                    }else{
                        $this->success('操作成功');
                    }
                }else{
                    $this->error('操作失败');
                }
            }
            else{
                $this->error('请勿重复操作');
            }



        }

    }


    /*
       * 发送消息接口  公共模版
       * $openid   家长的openid
       * $name     学生的姓名
       * wangtiantian
       */
    public function publish_ok1($openid,$name,$sta_name)
    {

        // 第一个参数  家长的 openid  第二个参数  学生的姓名
        $data_arr = Db::name('parent')
            ->where('openid', $openid)
            ->find();

        if ($data_arr) {

            $weixin = new  Weixin($this->shop_id);
            $openid = $data_arr['openid'];

            // 调用消息模版
            $re     = $this->getWxTemplate();

            $res    = json_decode($re, true);
            // 选择相对应的消息模版
            $templete_id = $res['sign_send'];

            $url    = Request()->domain() . '/store/teacher.index/index';


//            $data_arr1['first'] = ['value' => '您好，亲爱的家长', 'color' => '#173177'];
//            $data_arr1['keyword1'] = ['value' => "您的孩子" . $name . "已到校", 'color' => '#ff8a5a'];
//            $data_arr1['remark'] = ['value' => '此为提示信息,请以实际情况为准。', 'color' => '#173177'];

            $data_arr1['first'] = ['value' => '您好，亲爱的家长', 'color' => '#173177'];
            $data_arr1['childName'] = ['value' => $name , 'color' => '#ff8a5a'];
            $data_arr1['time'] = ['value' => date('Y-m-d H:i:s',time()), 'color' => '#ff8a5a'];
            $data_arr1['status'] = ['value' => $sta_name, 'color' => '#ff8a5a'];
            $data_arr1['remark'] = ['value' => '此为提示信息,请以实际情况为准。', 'color' => '#173177'];

            $re = $weixin->sentMsg($openid, $templete_id, $url, $data_arr1);


            if ($re['errcode'] != 0) {
                return $this->error("错误代码" . $re['errcode']);
            }
        }
    }


    /*
     * 检索提示框
     * wangtiantian
     */
    public  function  check(){
        if(request()->isAjax()){


            $keywords=input('keywords');

//            $myrs=mysql_query("select * from users where truename like '".$keywords."%'");
            $myrs=Db::name('student')->where('name|stu_no' ,'like','%'.$keywords.'%')->select();


            if($myrs)
            {
//                while($row=mysql_fetch_array($myrs))
//                {
//                    $temp[]=$row;
//                }

                foreach ($myrs  as $k => $v){
                    $temp[$k]['stu_no']=$v['stu_no'];
                    $temp[$k]['name']=$v['name'];
//                    $temp[]=123;
                }
//                echo "<pre>";
//                print_r($temp);
//                die;

//                halt($temp);
//                return json(['code'=>1, 'data' => $temp]);

                $this->success('','',$temp);
//                echo(json_encode($temp));
            }
        }
    }




}
